package com.permissions.dispatcher.sample.slice;

import com.permissions.dispatcher.annotation.*;
import com.permissions.dispatcher.sample.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.window.dialog.ToastDialog;
import ohos.bundle.IBundleManager;

@RuntimePermissions
public class MainAbilitySlice extends AbilitySlice {

    public static final String CAMERA_PERMISSION_NAME ="ohos.permission.CAMERA";

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_slice_main);

        Button buttonStart = (Button) findComponentById(ResourceTable.Id_btn_main_slice_apply);
        buttonStart.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                com.permissions.dispatcher.sample.slice.MainAbilitySlicePermissionsDispatcher.handlePermissionNewWithPermissionCheck(MainAbilitySlice.this);
            }
        });

        Button buttonJudge = (Button) findComponentById(ResourceTable.Id_btn_main_slice_judge);
        buttonJudge.setClickedListener(new Component.ClickedListener() {
            @Override
            public void onClick(Component component) {
                judgePermission();
            }
        });
    }

    /**
     * 申请权限
     */

    @NeedsPermission(CAMERA_PERMISSION_NAME)
    public void handlePermissionNew() {
        ToastUtil("申请权限成功了");
    }


    @OnPermissionDenied(CAMERA_PERMISSION_NAME)
    public void toResetPermission() {
        ToastUtil("OnPermissionDenied权限被拒绝了");
    }

    @OnShowRationale(CAMERA_PERMISSION_NAME)
    public void showDialog(PermissionRequest request) {
        ToastUtil("showDialog解释你需要你打开相应权限原因,需要写dialog弹框选择");
        //确定申请
        request.proceed();
        //取消
//        request.cancel();
    }

    @OnNeverAskAgain(CAMERA_PERMISSION_NAME)
    public void toExplainPermission() {
        ToastUtil("OnNeverAskAgain解释这个权限为什么被拒绝");
    }

    /**
     * 是否相应权限
     */
    public void judgePermission() {
        if (verifySelfPermission(CAMERA_PERMISSION_NAME) != IBundleManager.PERMISSION_GRANTED) {
            ToastUtil("还没有获取相机权限");
        }else {
            ToastUtil("已经获取了相机权限");
        }
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    public void ToastUtil(String i) {
        ToastDialog dialog = new ToastDialog(getContext());
        dialog.setContentText(i);
        dialog.setDuration(2000);
        dialog.show();
    }
}
